/**
 * Welcome to Cloudflare Workers! This is your first worker.
 *
 * - Run `npm run dev` in your terminal to start a development server
 * - Open a browser tab at http://localhost:8787/ to see your worker in action
 * - Run `npm run deploy` to publish your worker
 *
 * Learn more at https://developers.cloudflare.com/workers/
 */

import { Router } from 'itty-router';
import { verifyToken, generateToken } from './utils/jwt';
import { handleVerification } from './handlers/verification.js';
import { handleAccounts } from './handlers/accounts.js';
import { handleScan } from './handlers/scan.js';
import { handleScanClient } from './handlers/scan_client.js';
import AuthService from './utils/serverAuth';

// 创建路由器
const router = Router();

// CORS 中间件
const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};

// 认证中间件
async function authMiddleware(request, env) {
  if (request.method === 'OPTIONS') return null;

  const authHeader = request.headers.get('Authorization');
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return new Response('Unauthorized', { status: 401 });
  }

  const token = authHeader.split(' ')[1];
  try {
    const payload = await verifyToken(token, env.jwtSecretLoginAPP);
    request.user = payload;
    return null;
  } catch (error) {
    return new Response('Invalid token', { status: 401 });
  }
}

// 错误处理中间件
function errorHandler(error) {
  console.error('Error:', error);
  return new Response(JSON.stringify({
    code: 500,
    message: 'Internal Server Error'
  }), {
    status: 500,
    headers: {
      'Content-Type': 'application/json',
      ...corsHeaders
    }
  });
}

// 路由定义
router
  // 扫码客户端接口 (微信小程序、抖音小程序、APP等)
  .post('/api/scan_client/login', (req, env) => handleScanClient.login(req, env, new AuthService(env)))
  .post('/api/scan_client/token/verify', async (request, env) => {
    const { token } = await request.json();
    try {
      await verifyToken(token, env.jwtSecretLoginAPP);
      return new Response(JSON.stringify({ code: 200, valid: true }));
    } catch {
      return new Response(JSON.stringify({ code: 200, valid: false }));
    }
  })
  .post('/api/scan_client/token/refresh', async (request, env) => {
    const { refreshToken } = await request.json();
    try {
      const payload = await verifyToken(refreshToken, env.jwtSecretLoginAPP);
      const newToken = await generateToken(payload, env.jwtSecretLoginAPP, '1h');
      const newRefreshToken = await generateToken(payload, env.jwtSecretLoginAPP, '7d');
      
      return new Response(JSON.stringify({
        code: 200,
        data: { token: newToken, refreshToken: newRefreshToken }
      }));
    } catch {
      return new Response(JSON.stringify({ code: 401, message: 'Invalid refresh token' }));
    }
  })
  .post('/api/scan_client/verification/request', (req, env) => handleVerification.request(req, env, new AuthService(env)))
  .post('/api/scan_client/verification/verify', (req, env) => handleVerification.verify(req, env, new AuthService(env)))
  .get('/api/scan_client/accounts', authMiddleware, (req, env) => handleAccounts.list(req, env, new AuthService(env)))
  .post('/api/scan_client/scan/validate', (req, env) => handleScan.validate(req, env, new AuthService(env)))
  .post('/api/scan_client/scan/status', authMiddleware, (req, env) => handleScan.updateStatus(req, env, new AuthService(env)))
  .post('/api/scan_client/scan/authorize', authMiddleware, (req, env) => handleScan.authorize(req, env, new AuthService(env)))
  
  // 目标应用客户端接口
  .post('/api/target_client/login', (req, env) => handleAccounts.login(req, env, new AuthService(env)))
  .post('/api/target_client/token/verify', async (request, env) => {
    const { token } = await request.json();
    try {
      await verifyToken(token, env.jwtSecretLoginAPP);
      return new Response(JSON.stringify({ code: 200, valid: true }));
    } catch {
      return new Response(JSON.stringify({ code: 401, message: 'Invalid token' }));
    }
  })
  .post('/api/target_client/token/refresh', async (request, env) => {
    const { refreshToken } = await request.json();
    try {
      const payload = await verifyToken(refreshToken, env.jwtSecretLoginAPP);
      const newToken = await generateToken(payload, env.jwtSecretLoginAPP, '1h');
      const newRefreshToken = await generateToken(payload, env.jwtSecretLoginAPP, '7d');
      
      return new Response(JSON.stringify({
        code: 200,
        data: { token: newToken, refreshToken: newRefreshToken }
      }));
    } catch {
      return new Response(JSON.stringify({ code: 401, message: 'Invalid refresh token' }));
    }
  })
  .post('/api/target_client/bind_account', authMiddleware, (req, env) => handleAccounts.bind(req, env, new AuthService(env)));

// 导出 fetch 处理函数
export default {
  async fetch(request, env, ctx) {
    if (request.method === 'OPTIONS') {
      return new Response(null, {
        headers: corsHeaders
      });
    }

    try {
      const response = await router.handle(request, env, ctx);
      const headers = {
        'Content-Type': 'application/json',
        ...corsHeaders
      };
      
      return new Response(response.body, {
        status: response.status,
        headers
      });
    } catch (error) {
      return errorHandler(error);
    }
  }
};
